import React from 'react';
import {injectIntl, language} from './intl';
import {Table, Form, Row, Col, Modal, Alert} from 'antd';
import PropTypes from 'prop-types';
import {
    PAGE,
    TABLE,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    FIXED_COLUMN_WIDTH,
    FORM_OPTIONS,
    FORM_ROW_OPTIONS,
} from '../constants';
import styles from './style.css';
import routes from './routes';
import {Link} from 'react-router-dom';
import {hasPermissions} from './utils';
import {dutyUnitStatus, isTorF} from '../Enum';
import {conventEnumValueToString} from '../utils';
import {PERMISSION} from './constants';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {updateInfo} from './api';
import TextInput from 'Shared/components/TextInput';
const isTorFList = isTorF.toList(language);

const autosize = {minRows: 1};
import WrappedSelect from '../common/WrappedSelect';
const FormItem = Form.Item;
export class TablePanel extends React.PureComponent {
    state = {
        loading: false,
        showPanel: false,
        isValidate: false,
        isNeedPicture: true,
        brandId: '',
        name: '',
        remark: '',
        currentId: '',
    }

    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    }
    handleFilterChange = (value, name) => {
        this.setState({
            [name]: value
        });
    }

    handleStart = id => {
        this.setState({
            loading: true
        });
        this.props.onClickStart(id).then(() => {
            this.setState({
                loading: false
            });
        });
    }

    handleStop = id => {
        this.setState({
            loading: true
        });
        this.props.onClickStop(id).then(() => {
            this.setState({
                loading: false
            });
        });
    }

    onClickEdit = e => {
        const {id} = e.target.dataset;
        const {name, brandId, remark, isNeedPicture} = this.props.data.find(item => item.id === id);
        this.setState({
            name,
            brandId,
            remark,
            isNeedPicture,
            currentId: id,
            showPanel: true,
        });
    }

    onCancel = () => {
        this.setState({
            code: '',
            name: '',
            remark: '',
            brandId: '',
            currentId: '',
            isNeedPicture: true,
            isValidate: false,
            showPanel: false
        });
    }
    onSubmit = () => {
        const {name, brandId, remark, currentId, isNeedPicture} = this.state;
        if(!currentId) return;
        if(!name || !brandId)
            return this.setState({
                isValidate: true,
            });
        this.setState({
            loading: true
        });
        const {rowVersion} = this.props.data.find(item => item.id === currentId) || {};
        return updateInfo(currentId, {
            name,
            brandId,
            remark,
            rowVersion,
            isNeedPicture,
        }).then(res => {
            this.setState({
                loading: false,
            });
            if(res.ok) {
                this.onCancel();
                this.props.querySearch();
            }
        });
    }
    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({
                pageIndex: pagination.current - 1,
                pageSize: pagination.pageSize,
                sortedColumnKey: sorter.columnKey,
                sortedOrder: sorter.order,
            });
    };

    render() {
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '索赔供应商编号'
                }),
                dataIndex: 'code',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
                render: (text, record) => <Link to={routes.detail.format(record.id)} >{text}</Link>
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.name',
                    defaultMessage: '索赔供应商名称'
                }),
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'name' && this.props.sortedOrder,
                dataIndex: 'name'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.brandCode',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(dutyUnitStatus, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.isNeedPicture',
                    defaultMessage: '是否需要图片'
                }),
                dataIndex: 'isNeedPicture',
                render: text => conventEnumValueToString(isTorF, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [
                        {
                            id: PERMISSION.update,
                            children: (
                                <Link key="update" to={routes.update.format(r.id)}>
                                    {this.props.intl.formatMessage({
                                        id: 'tablePanel.operation.update',
                                        defaultMessage: '编辑'
                                    })}
                                </Link>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                        },
                        {
                            id: PERMISSION.start,
                            children: ref =>
                                <WrappedPopconfirm
                                    id={r.id}
                                    key="start"
                                    title={this.props.intl.formatMessage({
                                        id: 'tablePanel.popconfirm.message',
                                        defaultMessage: '是否继续?'
                                    })}
                                    onVisibleChange={ref.setMenuVisible}
                                    onConfirm={this.handleStart}>
                                    <a key="start">
                                        {this.props.intl.formatMessage({
                                            id: 'tablePanel.operation.start',
                                            defaultMessage: '启用'
                                        })}
                                    </a>
                                </WrappedPopconfirm>,
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.start) && hasPermissions(r.options, PERMISSION.start))
                        },
                        {
                            id: PERMISSION.stop,
                            children: ref =>
                                <WrappedPopconfirm
                                    id={r.id}
                                    key="stop"
                                    title={this.props.intl.formatMessage({
                                        id: 'tablePanel.popconfirm.message',
                                        defaultMessage: '是否继续?'
                                    })}
                                    onVisibleChange={ref.setMenuVisible}
                                    onConfirm={this.handleStop}>
                                    <a key="stop">
                                        {this.props.intl.formatMessage({
                                            id: 'tablePanel.operation.stop',
                                            defaultMessage: '停用'
                                        })}
                                    </a>
                                </WrappedPopconfirm>,
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.stop) && hasPermissions(r.options, PERMISSION.stop))
                        },
                    ];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            }
        ];
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE} />
            </div>
        );
    }
}
TablePanel.propTypes = {
    brands: PropTypes.array.isRequired,
    data: PropTypes.array.isRequired,
    errorMessage: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onClickStart: PropTypes.func.isRequired,
    onClickStop: PropTypes.func.isRequired,
    onPageIndexChange: PropTypes.func.isRequired,
    onPageSizeChange: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch, onClickStop, onClickStart, querySearch} from './actions';
import {createSelector} from 'reselect';
const EMPTY_ARRAY = [];
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getBrandsData = createSelector(
    state => state.getIn(['page', 'domainData', 'brands', 'data']),
    initData => {
        const data = initData.toJS() || EMPTY_ARRAY;
        return data.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        }));
    }
);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    brands: getBrandsData(state),
    permissions: getPermissions(state),
    querySearch: PropTypes.func.isRequired,
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
});

const mapDispatchToProps = dispatch => ({
    querySearch: () => dispatch(querySearch()),
    onPageSizeChange: (pageIndex, pageSize) =>
        dispatch(
            tableSearch({
                pageIndex: PAGE.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    onChangeSort: option => dispatch(tableSearch(option)),
    onClickStop: id =>
        dispatch(onClickStop(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onClickStart: id =>
        dispatch(onClickStart(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(TablePanel));
